<template>
  <Page>
    <el-card :bordered="false" class="mb-3">
      <ProSearchGroup
        isReset
        :options="searchOptions"
        :selectProps="{ style: { width: '160px' }, value: searchValue }"
        :inputProps="{ placeholder: '请输入账号名' }"
        @submit="searchGroupSubmit"
      />
    </el-card>
    <el-card :bordered="false" class="proCard">
      <Table
        :columns="columns"
        :request="loadDataTable"
        rowKey="id"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        autoScrollX
        virtual-scroll
      >
        <template #tableTitle>
          <el-space>
            <el-button type="primary" @click="openCreateDrawer">
              <template #icon>
                <el-icon>
                  <PlusOutlined />
                </el-icon>
              </template>
              新增
            </el-button>
          </el-space>
        </template>
      </Table>
    </el-card>

    <CreateDrawer ref="createDrawerRef" :title="drawerTitle" @change="reloadTable" />

    <ViewDrawer ref="viewDrawerRef" />
  </Page>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Table, BasicColumn, TableAction } from '@/design/components/Table';
  import { userList, deleteUser } from '@/api/system/user';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import CreateDrawer from './CreateDrawer.vue';
  import ViewDrawer from './ViewDrawer.vue';
  import { ProSearchGroup } from '@/components/ProSearchGroup';

  const basicTableRef = ref();
  const rowKeys = ref([]);
  const rowKeysName = ref([]);
  const tableData = ref();
  const createDrawerRef = ref();
  const drawerTitle = ref('新增');
  const viewDrawerRef = ref();
  const searchValue = ref('uid');

  const params = ref({
    searchKey: 'uid',
    searchValue: '',
  });

  const searchOptions = [
    {
      label: '账号',
      value: 'uid',
    },
  ];

  const actionColumn: BasicColumn = reactive({
    width: 180,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    align: 'center',
    render({ row: record }) {
      return h(TableAction as any, {
        actions: [
          {
            label: '查看',
            type: 'text',
            class: 'mr',
            onClick: handleView.bind(null, record),
            // auth: ['system:user:view'],
          },
          {
            label: '编辑',
            type: 'text',
            onClick: handleEdit.bind(null, record),
            // auth: ['system:user:modify'],
          },
          {
            label: '删除',
            isConfirm: true,
            type: 'text',
            popConfirm: {
              title: '您真的，确定要删除吗？',
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              onConfirm: handleDelete.bind(null, record),
            },
            // auth: ['system:user:delete'],
          },
        ],
      });
    },
  });

  /**
   * 搜索用户并提交表单
   * @param res - 搜索表单数据
   */
  function searchGroupSubmit(res) {
    params.value.searchKey = res.searchKey;
    params.value.searchValue = res.searchValue;
    reloadTable();
  }

  /**
   * 打开创建用户的抽屉
   */
  function openCreateDrawer() {
    drawerTitle.value = '新增';
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  /**
   * 加载用户数据表格
   * @param res - 表格数据补充参数
   * @returns 返回用户数据列表
   */
  const loadDataTable = async (res) => {
    const result = await userList({ ...params.value, ...res });
    tableData.value = result.list;
    return result;
  };

  /**
   * 处理选中的行数据
   * @param keys - 选中的行的键值
   */
  function onCheckedRow(keys) {
    rowKeys.value = keys;
    rowKeysName.value = tableData.value
      .filter((item) => {
        return keys.includes(item.id);
      })
      .map((item) => {
        return item.username;
      })
      .join('，');
  }

  /**
   * 重新加载数据表格
   */
  function reloadTable() {
    basicTableRef.value.reload();
  }

  /**
   * 打开查看用户信息的抽屉
   * @param record - 记录对象
   */
  function handleView(record: Recordable) {
    viewDrawerRef.value.openDrawer(record.id);
  }

  /**
   * 打开编辑用户抽屉
   * @param row - 行数据
   */
  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    drawerTitle.value = '编辑';
    const { openDrawer } = createDrawerRef.value;
    openDrawer(record.id);
  }

  /**
   * 删除用户
   * @param row - 行数据
   */
  function handleDelete(record: Recordable) {
    deleteUser(record.id).then(() => {
      ElMessage.success('删除成功');
      reloadTable();
    });
  }
</script>

<style lang="scss" scoped></style>
